import json
import os
import SimpleITK as sitk
import subprocess

json_d = {}
study_folder = r"D:\BaiduNetdiskDownload\dicom_data_test"
json_path = r"D:\Projects\heart-ca-project\Test\DicomFileJson.json"
output_path = r"D:\BaiduNetdiskDownload\dicom_data_output"


def create_deal_json():
    for each_dir in os.listdir(study_folder):
        abs_dir = os.path.join(study_folder, each_dir)

        reader = sitk.ImageSeriesReader()
        series_id = reader.GetGDCMSeriesIDs(abs_dir)[-1]
        files = reader.GetGDCMSeriesFileNames(abs_dir, series_id)
        file_format = "DCMTK"  # 还有一个 GDCM
        save_path = os.path.join(output_path, each_dir + ".nrrd")

        json_d[each_dir] = {
            "files": files,
            "format": file_format,
            "output": save_path
        }

    with open(json_path, "w", encoding='utf-8') as json_file:
        json_file.write(json.dumps(json_d))
    print("Created json file {}".format(json_path))


def create_deal_json_v2(dicom_dir, save_dir, json_path):
    root_dcm_dict = {}

    for root, dirs, files in os.walk(dicom_dir):
        filter_dcm_file = []
        for each_file in files:
            if each_file.lower().endswith(".dcm"):
                filter_dcm_file.append(each_file)

        if len(filter_dcm_file) == 0:
            continue


        reader = sitk.ImageSeriesReader()
        root_dcm_dict[root] = reader.GetGDCMSeriesIDs(root)[-1]
        series_file_names = reader.GetGDCMSeriesFileNames(root, root_dcm_dict[root])

        each_dir = os.path.basename(root)
        file_format = "DCMTK"
        save_path = os.path.join(save_dir, each_dir + '.nrrd')
        json_d[each_dir] = {
            "files": series_file_names,
            "format": file_format,
            "output": save_path
        }
        print(each_dir)

    with open(json_path, "w", encoding='utf-8') as json_file:
        json_file.write(json.dumps(json_d))
    print("Created json file {}".format(json_path))



slicer_exe = r"D:\IDEs\Slicer 5.8.1\Slicer.exe"
script_path = r"D:\Projects\heart-ca-project\Test\DcmConvertWithSlicerGBK.py"


def run_slicer_script():
    command = [
        slicer_exe,
        "--python-script",
        script_path,
        json_path
    ]
    result = subprocess.run(command)
    print(result.returncode)

# create_deal_json()
create_deal_json_v2(study_folder, output_path, json_path)
run_slicer_script()
